# coding=utf-8
# author:hhu_zym(qq:1045797922)
# 动脑学院VIP学员

'''
1.计算range(1,99999)的总和,采取三种方式,第一:重复10次计算总时间;
 第二:开启十个子线程去计算;第三:开启十个进程去计算,然后对比耗时
'''
# import time
# 第一:重复10次计算总时间
# time1=time.time()
# for num in range(1,11):
#     result=sum(range(1,99999))
# time2=time.time()
# print('方案一花费时间：%s' % str(time2-time1)) # 方案一花费时间：0.027019739151000977

# 第二:开启十个子线程去计算
# from threading import Thread,current_thread
# def sum_calculate(num):
#     result=sum(range(1,101))
# thread_list=[Thread(target=sum_calculate,args=(num,)) for num in range(1,11)]
# time1=time.time()
# for thr in thread_list:
#     thr.start()
#     thr.join()
# time2=time.time()
# print('方案二花费时间：%s' % str(time2-time1))  # 方案二花费时间：0.0010008811950683594

# 第三:开启十个进程去计算
# from multiprocessing import Process,Pool
# def sum_calculate():
#     result=sum(range(1,99999))
# if __name__=='__main__':
#     pool=Pool(10)
#     time1=time.time()
#     for num in range(1,11):
#         pool.apply_async(sum_calculate,args=())
#     pool.close()
#     pool.join()
#     time2=time.time()
#     print('方案三花费时间：%s' % str(time2-time1))  # 方案三花费时间：0.7815523147583008

# 2.将第一题计算十次改为使用线程池去计算,线程池线程个数由你自己电脑cpu逻辑核数决定
from threadpool import ThreadPool,makeRequests
import time
def sum_calculate(num):
    result=sum(range(1,99999))
pool=ThreadPool(8)  # 四核八线程
a_list=list(range(1,11))
request_list=makeRequests(sum_calculate,a_list)
time1=time.time()
for req in request_list:
    pool.putRequest(req)
pool.wait()
time2=time.time()
print('线程池花费时间%s' % str(time2-time1))  # 线程池花费时间0.02601766586303711

